package com.chy.blog_web.modular.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.blog_web.core.util.SendSmsUtil;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.mapper.BoSeeBookMapper;
import com.chy.blog_web.modular.web.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 描述：约看书表 service业务层
 * 作者：chenhuiyan
 * 时间：2020/04/11
 */
@Service
@Transactional(readOnly = true)
public class BoSeeBookServiceImpl extends ServiceImpl<BoSeeBookMapper, BoSeeBook> implements IBoSeeBookService {

    Logger logger = LoggerFactory.getLogger(BoSeeBookServiceImpl.class);

    @Autowired
    private IBoInfoSendMrgService infoSendMrgService;

    @Autowired
    private IBoDynamicService dynamicService;

    @Autowired
    private IBoBookService boBookService;

    @Autowired
    private IBoSpaceUserService spaceUserService;

    @Autowired
    private IBoMsgTemplateService msgTemplateService;

    @Autowired
    private IBoMsgSignService msgSignService;

    /**
     * 查询未写感受列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> list(Map<String, Object> params){
        return baseMapper.list(params);
    }

    /**
     * 查询未结束的列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> getList(Map<String, Object> params){
        return baseMapper.getList(params);
    }

    /**
     * 查询未写感受总数
     * @param params
     * @return
     */
    public int getCount(Map<String, Object> params){
        return baseMapper.getCount(params);
    }

    /**
     * 查询详情
     * @param id
     * @return
     */
    public Map<String, Object> getInfoById(String id){
        return baseMapper.getInfoById(id);
    }

    /**
     * 查询亲蜜度
     * @return
     */
    public int getSweet(){
        return baseMapper.getSweet();
    }

    /**
     * 发起一起看书
     * @param seeBook
     */
    @Transactional
    public void sendSeeBook(BoSeeBook seeBook, BoSpaceUser spaceUser){

        //保存约看书清单
        seeBook.setSpaceUserId(spaceUser.getId());
        seeBook.preInsert();
        this.save(seeBook);

        //获取书名
        BoBook book = boBookService.getById(seeBook.getBookId());
        String bookName = book.getBookName();

        //生成一起看书清单动态
        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(seeBook.getStartTime());
        String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(seeBook.getEndTime());

        String content = "<span class='dy-content'>书名：《" + bookName + "》</span>";
        content += "<br/><span class='dy-content'>目录：" + seeBook.getDirectoryName() + "</span>";
        content += "<br/><span class='dy-content'>章节：" + seeBook.getBookListName() + "</span>";
        content += "<br/><span class='dy-content'>开始时间：" + startTime + "</span>";
        content += "<br/><span class='dy-content'>结束时间：" + endTime + "</span>";

        BoDynamic boDynamic = new BoDynamic();
        boDynamic.preInsert();
        boDynamic.setServiceId(seeBook.getId());
        boDynamic.setContent(content);
        boDynamic.setType(3);
        boDynamic.setSpaceUserId(spaceUser.getId());
        dynamicService.save(boDynamic);

        //**************************发送短信********************

        //空间用户他
        BoSpaceUser spaceUserToHe = spaceUserService.getOne(new QueryWrapper<BoSpaceUser>()
                .eq("type", 0)
                .ne("status", 2)
                .eq("del_flag", 0));

        //空间用户她
        BoSpaceUser spaceUserToHer = spaceUserService.getOne(new QueryWrapper<BoSpaceUser>()
                .eq("type", 1)
                .ne("status", 2)
                .eq("del_flag", 0));

        //手机号、接收人
        String[] phoneNumbers = {spaceUserToHe.getPhone(), spaceUserToHer.getPhone()};
        String[] receiveName = {spaceUserToHe.getUserName(), spaceUserToHer.getUserName()};

        //******************变量长度处理（不超过20）********************

        //书名
        bookName = "《" + bookName + "》";
        String bn = "";
        if(bookName.length() > 20){
            bn = bookName.substring(0, 17) + "...";
        }else{
            bn = bookName;
        }

        //目录名
        String directoryName = "";
        if(seeBook.getDirectoryName().length() > 20){
            directoryName = seeBook.getDirectoryName().substring(0, 17) + "...";
        }else{
            directoryName = seeBook.getDirectoryName();
        }

        //章节名
        String bookListName = "";
        if(seeBook.getBookListName().length() > 20){
            bookListName = seeBook.getBookListName().substring(0, 17) + "...";
        }else{
            bookListName = seeBook.getBookListName();
        }

        //获取签名
        BoMsgSign msgSign = msgSignService.getOne(new QueryWrapper<BoMsgSign>().eq("use_status", 0));
        String singName = SendSmsUtil.SIGNNAME_CODE;
        if(ObjectUtil.isNotEmpty(msgSign)){
            singName = msgSign.getSignName();
        }

        //获取模板信息
        String temCode = SendSmsUtil.TEMPLATE_CODE_SEE_BOOK;
        BoMsgTemplate msgTemplate = msgTemplateService.getOne(new QueryWrapper<BoMsgTemplate>().eq("code", temCode));

        if(ObjectUtil.isNotEmpty(msgTemplate)){
            //短信模板变量（变量属性:${userName} 在博客空间发起了一条看书清单，书名：${bookName}，目录：${directoryName}，章节：${listName}，开始时间：${startTime}，结束时间：${endTime}）
            JSONObject tJson = JSONUtil.createObj()
                    .put("userName", spaceUser.getUserName())
                    .put("bookName", bn)
                    .put("directoryName", directoryName)
                    .put("listName", bookListName)
                    .put("startTime", startTime)
                    .put("endTime", endTime);
            String templateParam = JSONUtil.toJsonStr(tJson);

            logger.info(">>>>>>>>>发起看书动态-短信模板变量tJson：{}", tJson);
            for(int i = 0; i < phoneNumbers.length; i++){
                logger.info(">>>>>>>>>发起看书动态-接收手机号：{}", phoneNumbers[i]);
                String dataStr = SendSmsUtil.SendSms(phoneNumbers[i], singName, temCode, templateParam);
                logger.info(">>>>>>>>>发起看书动态-发送结果：{}", dataStr);

                //生成信息发送记录
                infoSendMrgService.saveMsgLog(dataStr, msgTemplate, tJson, receiveName[i], phoneNumbers[i], 4, "");
            }
        }else{
            logger.info(">>>>>>>>>发起看书动态-短信模板不存在,无法发送短信：{}", temCode);
        }
    }

}
